from rest_framework import serializers
from django_redis import get_redis_connection

from user.models import User
from .utils import check_save_user_token
from .models import QQAuthUser


class QQAuthUserSerializer(serializers.Serializer):
    """定义qq登录验证的序列化器"""
    # 由于一下数据只做反序列化,所以统一设置write_only=True
    access_token = serializers.CharField(label='操作凭证', write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$', write_only=True)
    password = serializers.CharField(label='密码', max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)

    def validate(self, attrs):
        """检验参数"""
        # 1.获取加密后的openid,对加密后的openid进行解密
        print(123)
        access_token = attrs.get("access_token")
        if not access_token:
            raise serializers.ValidationError("access_token不存在")
        # 1.1 对access_token进行解密,解密后是一个字典,需要取出其中的openid
        access_token = check_save_user_token(access_token)
        # 1.2解密后将为 openid重新赋值给attrs
        attrs["access_token"] = access_token
        # 2.验证短信验证码
        mobile = attrs.get("mobile")
        sms_code = attrs.get("sms_code")
        # 2.1 链接redis数据库
        redis_restore = get_redis_connection("verify_codes")
        # 2.2 获取数据库储存的验证码,需要注意取出来的为bytes类型
        real_sms_code = redis_restore.get('sms_%s' % mobile).decode()
        if not real_sms_code:
            raise serializers.ValidationError("短信验证码过期")
        # 2.1 将用户输入的短信验证码和redis数据库中的验证码进行比较
        if real_sms_code != sms_code:
            raise serializers.ValidationError("短信验证码错误")
        # 3.根据手机号查询当前用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        # 3.1 如果当前用户不存在,则需要新增用户对象
        except User.DoesNotExist:
            pass
        # 3.2 如果存在直接,需要对密码进行校验
        else:
            if not user.check_password(attrs.get("password")):
                raise serializers.ValidationError("用户存在,但是密码错误")
            else:
                attrs["user"] = user

        return attrs

    def create(self, validated_data):
        """新增数据"""
        # 1.获取用户对象
        user = validated_data.get("user")
        # 2.如果用户不存在.直接创建用户对象
        if not user:
            user = User(
                username=validated_data.get("mobile"),
                mobile=validated_data.get("mobile"),
                password=validated_data.get("password")
            )
            user.set_password(validated_data.get("password"))
            user.save()
        # 3.将用户与openid进行绑定
        qq = QQAuthUser.objects.create(
            openid=validated_data.get("access_token"),
            user=user
        )
        # 返回用户数据做状态保持
        return user
        # class QQAuthUserSerializer(serializers.Serializer):
        #     """绑定用户的序列化器"""
        #
        #     access_token = serializers.CharField(label='操作凭证')
        #     mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
        #     password = serializers.CharField(label='密码', max_length=20, min_length=8)
        #     sms_code = serializers.CharField(label='短信验证码')
        #
        #
        #     def validate(self, attrs):
        #
        #         access_token = attrs.get('access_token')  # 获取出加密的openid
        #         openid = check_save_user_token(access_token)
        #         if not openid:
        #             raise serializers.ValidationError('openid无效')
        #         attrs['access_token'] = openid  # 把解密后的openid保存到反序列化的大字典中以备后期绑定用户时使用
        #
        #         # 验证短信验证码是否正确
        #         redis_conn = get_redis_connection('verify_codes')
        #         # 获取当前用户的手机号
        #         mobile = attrs.get('mobile')
        #         real_sms_code = redis_conn.get('sms_%s' % mobile)
        #         # 获取前端传过来的验证码
        #         sms_code = attrs.get('sms_code')
        #         if real_sms_code.decode() != sms_code:  # 注意redis中取出来的验证码是bytes类型注意类型处理
        #             raise serializers.ValidationError('验证码错误')
        #
        #         try:
        #             # 判断手机号是已存在用户的还是新用户
        #             user = User.objects.get(mobile=mobile)
        #         except User.DoesNotExist:
        #             # 如果出现异常说明是新用户
        #             pass
        #         else:
        #             # 表示此手机号是已注册过的用户
        #             if not user.check_password(attrs.get('password')):
        #                 raise serializers.ValidationError('已存在用户,但密码不正确')
        #             else:
        #                 attrs['user'] = user
        #
        #         return attrs
        #
        #     def create(self, validated_data):
        #         """把openid和user进行绑定"""
        #         user = validated_data.get('user')
        #         if not user:  # 如果用户是不存在的,那就新增一个用户
        #             user = User(
        #                 username=validated_data.get('mobile'),
        #                 password=validated_data.get('password'),
        #                 mobile=validated_data.get('mobile')
        #             )
        #             user.set_password(validated_data.get('password'))  # 对密码进行加密
        #             user.save()
        #
        #         # 让user和openid绑定
        #         QQAuthUser.objects.create(
        #             user=user,
        #             openid=validated_data.get('access_token')
        #         )
        #
        #         return user
